<template>
  <div class="certificate-issuance">
    <div class="issuance-header">
      <div class="header-left">
        <el-button type="primary" plain @click="goToHome">
          <el-icon><back /></el-icon>
          返回主页
        </el-button>
        <h2>证书颁发</h2>
      </div>
    </div>

    <div class="issuance-content">
      <!-- 步骤条 -->
      <el-steps :active="currentStep" finish-status="success" class="issuance-steps">
        <el-step title="选择考试"></el-step>
        <el-step title="设置颁发条件"></el-step>
        <el-step title="选择证书模板"></el-step>
        <el-step title="字段映射"></el-step>
        <el-step title="预览与确认"></el-step>
      </el-steps>

      <!-- 步骤1：选择考试 -->
      <div v-if="currentStep === 0" class="step-container">
        <h3>选择考试</h3>
        <el-table
          v-loading="loading"
          :data="examList"
          style="width: 100%"
          @row-click="handleExamSelect"
          highlight-current-row
        >
          <el-table-column prop="examId" label="考试ID" width="80" />
          <el-table-column prop="examName" label="考试名称" />
          <el-table-column prop="subject" label="科目" />
          <el-table-column prop="totalScore" label="总分" width="80" />
          <el-table-column prop="startTime" label="开始时间" width="180">
            <template #default="scope">
              {{ formatDate(scope.row.startTime) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="120">
            <template #default="scope">
              <el-button
                type="primary"
                size="small"
                @click.stop="selectExam(scope.row)"
              >
                选择
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        
        <!-- 添加分页组件 -->
        <div class="pagination-container">
          <el-pagination
            :current-page="currentPage"
            :page-size="pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>

      <!-- 步骤2：设置颁发条件 -->
      <div v-if="currentStep === 1" class="step-container">
        <h3>设置颁发条件</h3>
        <div class="condition-form">
          <el-form :model="issuanceCondition" label-width="120px">
            <el-form-item label="考试名称">
              <el-input v-model="selectedExam.examName" disabled />
            </el-form-item>
            <el-form-item label="合格分数线">
              <el-input-number 
                v-model="issuanceCondition.passThreshold" 
                :min="0" 
                :max="selectedExam.totalScore"
                :step="1"
              />
              <span class="threshold-description">分及以上颁发证书</span>
            </el-form-item>
          </el-form>
        </div>
      </div>

      <!-- 步骤3：选择证书模板 -->
      <div v-if="currentStep === 2" class="step-container">
        <h3>选择证书模板</h3>
        <div class="template-grid">
          <el-card
            v-for="template in templates"
            :key="template.templateId"
            :class="['template-card', selectedTemplateId === template.templateId ? 'selected' : '']"
            @click="selectTemplate(template.templateId)"
          >
            <div class="template-preview">
              <div class="preview-background">
                <img 
                  v-if="templateImages[template.templateId]"
                  :src="templateImages[template.templateId]"
                  class="background-image"
                  alt="模板背景"
                />
                <div 
                  v-for="field in template.fields" 
                  :key="field.fieldKey"
                  class="preview-field"
                  :style="{
                    left: `${field.percentX * 100}%`,
                    top: `${field.percentY * 100}%`,
                    fontSize: `${field.fontSize * 0.8}px`,
                    color: field.color,
                    fontWeight: field.fontWeight,
                    transform: 'translate(-50%, -50%)'
                  }"
                >
                  {{ field.previewText || field.label }}
                </div>
              </div>
              <div class="template-info">
                <div class="template-name">{{ template.templateName }}</div>
                <div class="template-date">创建时间: {{ formatDate(template.createTime) }}</div>
              </div>
            </div>
          </el-card>
        </div>
      </div>

      <!-- 步骤4：字段映射 -->
      <div v-if="currentStep === 3" class="step-container">
        <h3>字段映射</h3>
        <div class="field-mapping">
          <div v-if="selectedTemplateId && selectedTemplateFields.length > 0">
            <el-form label-width="120px">
              <el-form-item 
                v-for="field in selectedTemplateFields" 
                :key="field.fieldKey" 
                :label="field.label"
              >
                <!-- 正文字段使用文本域 -->
                <el-input 
                  v-if="isContentField(field)" 
                  v-model="fieldMapping[field.fieldKey]" 
                  type="textarea" 
                  :rows="3"
                  placeholder="请输入证书正文内容"
                />
                <!-- 颁发机构字段使用输入框 -->
                <el-input 
                  v-else-if="isIssuerField(field)" 
                  v-model="fieldMapping[field.fieldKey]" 
                  placeholder="请输入颁发机构"
                />
                <!-- 颁发日期字段使用日期选择器 -->
                <el-date-picker
                  v-else-if="isDateField(field)"
                  v-model="fieldMapping[field.fieldKey]"
                  type="date"
                  placeholder="选择日期"
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD"
                />
                <!-- 姓名和证书编号字段使用禁用的输入框 -->
                <el-input
                  v-else-if="isNameField(field) || isCodeField(field)"
                  v-model="fieldMapping[field.fieldKey]"
                  disabled
                  :placeholder="isNameField(field) ? '学生姓名（自动生成）' : '证书编号（自动生成）'"
                />
                <!-- 其他字段使用下拉选择 -->
                <el-select 
                  v-else
                  v-model="fieldMapping[field.fieldKey]" 
                  placeholder="请选择映射字段"
                >
                  <el-option label="考试名称" value="examName" />
                  <el-option label="考试成绩" value="score" />
                  <el-option label="考试日期" value="examDate" />
                </el-select>
              </el-form-item>
            </el-form>
          </div>
          <el-empty v-else description="请先选择证书模板" />
        </div>
      </div>

      <!-- 步骤5：预览与确认 -->
      <div v-if="currentStep === 4" class="step-container">
        <h3>预览与确认</h3>
        <div class="preview-summary">
          <el-descriptions title="颁发配置摘要" :column="2" border>
            <el-descriptions-item label="考试名称">{{ selectedExam.examName }}</el-descriptions-item>
            <el-descriptions-item label="考试科目">{{ selectedExam.subject }}</el-descriptions-item>
            <el-descriptions-item label="合格分数线">{{ issuanceCondition.passThreshold }}分及以上</el-descriptions-item>
            <el-descriptions-item label="证书模板">{{ getTemplateName(selectedTemplateId) }}</el-descriptions-item>
          </el-descriptions>
          
          <el-divider content-position="center">颁发预览</el-divider>
          
          <div v-loading="previewLoading" class="preview-list">
            <el-empty v-if="previewData.length === 0" description="没有符合条件的学生" />
            <el-table v-else :data="previewData" style="width: 100%">
              <el-table-column prop="studentName" label="学生姓名" />
              <el-table-column prop="score" label="考试分数" />
              <el-table-column prop="certificateCode" label="证书编号" />
            </el-table>
          </div>
        </div>
      </div>

      <!-- 步骤按钮 -->
      <div class="step-actions">
        <el-button v-if="currentStep > 0" @click="prevStep">上一步</el-button>
        <el-button 
          v-if="currentStep < 4" 
          type="primary" 
          @click="nextStep"
          :disabled="!canProceed"
        >
          下一步
        </el-button>
        <el-button 
          v-else 
          type="success" 
          @click="confirmIssuance"
          :loading="issuanceLoading"
        >
          确认颁发
        </el-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, reactive, watch } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Back, Trophy, Medal, Check } from '@element-plus/icons-vue'
import { getTemplatesByCreator } from '../../api/dashboard'
import { getFinishedExams, getExamDetail, previewCertificateIssuance, issueCertificates } from '../../api/certificate'
import * as pdfjsLib from 'pdfjs-dist'

// 设置 pdf.js worker 路径
pdfjsLib.GlobalWorkerOptions.workerSrc = `https://cdnjs.cloudflare.com/ajax/libs/pdf.js/${pdfjsLib.version}/pdf.worker.min.js`

const router = useRouter()
const currentStep = ref(0)
const loading = ref(false)
const issuanceLoading = ref(false)

// 考试列表
const examList = ref([])
const selectedExam = ref({})

// 证书模板列表
const templates = ref([])
const selectedTemplateId = ref(null)
const templateImages = ref({}) // 存储模板预览图的URL

// 颁发条件
const issuanceCondition = reactive({
  passThreshold: 60
})

// 字段映射
const fieldMapping = reactive({})

// 预览数据
const previewData = ref([])
const previewLoading = ref(false)

// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 返回主页
const goToHome = () => {
  router.push('/main')
}

// 获取模板名称
const getTemplateName = (templateId) => {
  if (!templateId) return '未选择'
  const template = templates.value.find(t => t.templateId === templateId)
  return template ? template.templateName : '未知模板'
}

// 获取级别标签
const getLevelLabel = (level) => {
  const labels = {
    excellent: '优秀证书',
    good: '良好证书',
    pass: '合格证书'
  }
  return labels[level] || level
}

// 获取选中模板的字段
const selectedTemplateFields = computed(() => {
  if (!selectedTemplateId.value) return []
  const template = templates.value.find(t => t.templateId === selectedTemplateId.value)
  return template && template.fields ? template.fields : []
})

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return '未知'
  const date = new Date(dateString)
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
}

// 加载考试列表
const loadExams = async () => {
  loading.value = true
  try {
    const userInfo = JSON.parse(localStorage.getItem('userInfo'))
    const response = await getFinishedExams(userInfo.schoolNumber, currentPage.value, pageSize.value)
    if (response.code === 200) {
      examList.value = response.data.records
      total.value = response.data.total
    } else {
      ElMessage.error(response.message || '获取考试列表失败')
    }
  } catch (error) {
    console.error('获取考试列表失败:', error)
    ElMessage.error('获取考试列表失败')
  } finally {
    loading.value = false
  }
}

// 选择考试
const selectExam = async (exam) => {
  try {
    loading.value = true
    const response = await getExamDetail(exam.examId)
    if (response.code === 200) {
      selectedExam.value = response.data
      nextStep()
    } else {
      ElMessage.error(response.message || '获取考试详情失败')
    }
  } catch (error) {
    console.error('获取考试详情失败:', error)
    ElMessage.error('获取考试详情失败，请重试')
  } finally {
    loading.value = false
  }
}

// 处理考试行点击
const handleExamSelect = (row) => {
  selectedExam.value = row
}

// 判断字段类型的辅助函数
const isContentField = (field) => {
  if (!field || !field.fieldKey) return false;
  const key = field.fieldKey.toLowerCase();
  const label = field.label ? field.label.toLowerCase() : '';
  return key.includes('content') || label.includes('正文') || label.includes('内容');
}

const isNameField = (field) => {
  const key = field.fieldKey.toLowerCase()
  const label = field.label.toLowerCase()
  return key.includes('name') || key.includes('student') || label.includes('姓名') || label.includes('名字')
}

const isCodeField = (field) => {
  const key = field.fieldKey.toLowerCase()
  const label = field.label.toLowerCase()
  return key.includes('code') || key.includes('number') || label.includes('编号') || label.includes('编码')
}

const isDateField = (field) => {
  if (!field || !field.fieldKey) return false;
  const key = field.fieldKey.toLowerCase();
  const label = field.label ? field.label.toLowerCase() : '';
  return key.includes('date') || key.includes('time') || label.includes('日期') || label.includes('时间');
}

const isIssuerField = (field) => {
  if (!field || !field.fieldKey) return false;
  const key = field.fieldKey.toLowerCase();
  const label = field.label ? field.label.toLowerCase() : '';
  return key.includes('issuer') || key.includes('org') || label.includes('机构') || label.includes('颁发者');
}

// 选择证书模板
const selectTemplate = (templateId) => {
  selectedTemplateId.value = templateId
  
  // 重置字段映射
  Object.keys(fieldMapping).forEach(key => {
    delete fieldMapping[key]
  })
  
  // 为每个字段设置默认映射
  const template = templates.value.find(t => t.templateId === templateId)
  if (template && template.fields) {
    template.fields.forEach(field => {
      if (isContentField(field)) {
        // 正文字段使用空字符串作为默认值，让用户输入
        fieldMapping[field.fieldKey] = ''
      } else if (isNameField(field)) {
        // 姓名字段锁定为studentName
        fieldMapping[field.fieldKey] = 'studentName'
      } else if (isCodeField(field)) {
        // 证书编号字段锁定为certificateCode
        fieldMapping[field.fieldKey] = 'certificateCode'
      } else if (isDateField(field)) {
        // 日期字段默认为当前日期
        const today = new Date()
        const year = today.getFullYear()
        const month = String(today.getMonth() + 1).padStart(2, '0')
        const day = String(today.getDate()).padStart(2, '0')
        fieldMapping[field.fieldKey] = `${year}-${month}-${day}`
      } else if (isIssuerField(field)) {
        // 颁发机构字段默认为空，让用户输入
        fieldMapping[field.fieldKey] = ''
      } else if (field.fieldKey.toLowerCase().includes('exam') || field.label.toLowerCase().includes('考试')) {
        fieldMapping[field.fieldKey] = 'examName'
      } else if (field.fieldKey.toLowerCase().includes('score') || field.label.toLowerCase().includes('成绩')) {
        fieldMapping[field.fieldKey] = 'score'
      } else {
        fieldMapping[field.fieldKey] = ''
      }
    })
  }
}

// 是否可以进行下一步
const canProceed = computed(() => {
  switch (currentStep.value) {
    case 0:
      return !!selectedExam.value.examId
    case 1:
      return issuanceCondition.passThreshold !== null
    case 2:
      return selectedTemplateId.value !== null
    case 3:
      // 检查是否所有字段都已映射或输入
      if (!selectedTemplateId.value) return false
      const template = templates.value.find(t => t.templateId === selectedTemplateId.value)
      if (!template || !template.fields || template.fields.length === 0) return true
      return template.fields.every(field => {
        // 对于正文和颁发机构字段，检查是否有输入内容
        if (isContentField(field) || isIssuerField(field)) {
          return fieldMapping[field.fieldKey] !== undefined && fieldMapping[field.fieldKey] !== ''
        }
        // 对于其他字段，检查是否有值
        return !!fieldMapping[field.fieldKey]
      })
    default:
      return true
  }
})

// 上一步
const prevStep = () => {
  if (currentStep.value > 0) {
    currentStep.value--
  }
}

// 下一步
const nextStep = async () => {
  if (currentStep.value < 4) {
    // 如果是从第二步进入第三步，加载证书模板列表
    if (currentStep.value === 1) {
      try {
        const userInfo = JSON.parse(localStorage.getItem('userInfo'))
        const response = await getTemplatesByCreator(userInfo.username)
        if (response.code === 200) {
          templates.value = response.data || []
          // 转换所有模板的PDF为图片
          for (const template of templates.value) {
            const imageUrl = await convertPdfToImage(template.backgroundPath)
            if (imageUrl) {
              templateImages.value[template.templateId] = imageUrl
            }
          }
        } else {
          ElMessage.error(response.message || '获取证书模板列表失败')
          return
        }
      } catch (error) {
        console.error('获取证书模板列表失败:', error)
        ElMessage.error('获取证书模板列表失败')
        return
      }
    }
    
    currentStep.value++
    
    if (currentStep.value === 4) {
      await loadPreviewData()
    }
  }
}

// 加载预览数据
const loadPreviewData = async () => {
  previewLoading.value = true;
  try {
    // 构建预览请求参数
    const params = {
      examId: selectedExam.value.examId,
      templateId: selectedTemplateId.value,
      passThreshold: issuanceCondition.passThreshold
    };
    
    // 添加自定义字段
    if (fieldMapping) {
      // 查找模板中的特定字段
      const contentField = selectedTemplateFields.value.find(field => isContentField(field));
      const issuerField = selectedTemplateFields.value.find(field => isIssuerField(field));
      const dateField = selectedTemplateFields.value.find(field => isDateField(field));
      
      // 如果找到字段并且有对应的映射值，则添加到参数中
      if (contentField && fieldMapping[contentField.fieldKey]) {
        params.content = fieldMapping[contentField.fieldKey];
      }
      
      if (issuerField && fieldMapping[issuerField.fieldKey]) {
        params.issuer = fieldMapping[issuerField.fieldKey];
      }
      
      if (dateField && fieldMapping[dateField.fieldKey]) {
        params.issueDate = fieldMapping[dateField.fieldKey];
      }
    }
    
    const response = await previewCertificateIssuance(params);
    if (response.code === 200) {
      previewData.value = response.data || []
      if (previewData.value.length === 0) {
        ElMessage.warning('没有符合条件的学生')
      } else {
        ElMessage.success(`共有 ${previewData.value.length} 名学生符合颁发条件`)
      }
    } else {
      ElMessage.error(response.message || '获取预览数据失败')
    }
  } catch (error) {
    console.error('获取预览数据失败:', error)
    ElMessage.error('获取预览数据失败，请重试')
  } finally {
    previewLoading.value = false;
  }
}

// 确认颁发
const confirmIssuance = async () => {
  try {
    issuanceLoading.value = true;
    
    // 构建颁发请求参数
    const data = {
      examId: selectedExam.value.examId,
      templateId: selectedTemplateId.value,
      passThreshold: issuanceCondition.passThreshold,
      fieldMapping: fieldMapping
    };
    
    // 添加自定义字段
    if (fieldMapping) {
      // 查找模板中的特定字段
      const contentField = selectedTemplateFields.value.find(field => isContentField(field));
      const issuerField = selectedTemplateFields.value.find(field => isIssuerField(field));
      const dateField = selectedTemplateFields.value.find(field => isDateField(field));
      
      // 如果找到字段并且有对应的映射值，则添加到参数中
      if (contentField && fieldMapping[contentField.fieldKey]) {
        data.content = fieldMapping[contentField.fieldKey];
      }
      
      if (issuerField && fieldMapping[issuerField.fieldKey]) {
        data.issuer = fieldMapping[issuerField.fieldKey];
      }
      
      if (dateField && fieldMapping[dateField.fieldKey]) {
        data.issueDate = fieldMapping[dateField.fieldKey];
      }
    }
    
    const response = await issueCertificates(data);
    if (response.code === 200) {
      ElMessage.success(`成功颁发 ${response.data.length} 份证书！`);
      router.push('/certificate/list');
    } else {
      ElMessage.error(response.message || '证书颁发失败');
    }
  } catch (error) {
    console.error('证书颁发失败:', error);
    ElMessage.error('证书颁发失败，请重试');
  } finally {
    issuanceLoading.value = false;
  }
}

// 处理页码改变
const handleCurrentChange = (val) => {
  currentPage.value = val
  loadExams()
}

// 处理每页条数改变
const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
  loadExams()
}

// 将PDF转换为图片
const convertPdfToImage = async (pdfUrl) => {
  try {
    const proxyUrl = '/lcc/pdf' + pdfUrl.replace('https://syhsyh.oss-cn-chengdu.aliyuncs.com', '')
    const loadingTask = pdfjsLib.getDocument(proxyUrl)
    const pdf = await loadingTask.promise
    const page = await pdf.getPage(1) // 获取第一页
    
    const scale = 2 // 缩放比例，提高清晰度
    const viewport = page.getViewport({ scale })
    
    // 创建canvas
    const canvas = document.createElement('canvas')
    const context = canvas.getContext('2d')
    canvas.height = viewport.height
    canvas.width = viewport.width
    
    // 渲染PDF页面到canvas
    const renderContext = {
      canvasContext: context,
      viewport: viewport
    }
    await page.render(renderContext).promise
    
    // 将canvas转换为图片URL
    return canvas.toDataURL('image/jpeg', 0.8)
  } catch (error) {
    console.error('PDF转换为图片失败:', error)
    return null
  }
}

onMounted(() => {
  loadExams()
})
</script>

<style scoped>
.certificate-issuance {
  padding: 20px;
  min-height: 100vh;
  background: linear-gradient(135deg, #f5f7fa 0%, #e4e8eb 100%);
}

.issuance-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
  background-color: rgba(255, 255, 255, 0.8);
  padding: 15px 20px;
  border-radius: 10px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
}

.header-left {
  display: flex;
  align-items: center;
  gap: 20px;
}

.header-left h2 {
  margin: 0;
  color: #2c3e50;
}

.issuance-content {
  background-color: rgba(255, 255, 255, 0.8);
  border-radius: 10px;
  padding: 20px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
}

.issuance-steps {
  margin-bottom: 30px;
}

.step-container {
  margin-bottom: 30px;
}

.step-container h3 {
  margin-top: 0;
  margin-bottom: 20px;
  color: #2c3e50;
  border-bottom: 1px solid #ebeef5;
  padding-bottom: 10px;
}

.step-actions {
  display: flex;
  justify-content: center;
  gap: 20px;
  margin-top: 30px;
  padding-top: 20px;
  border-top: 1px solid #ebeef5;
}

.condition-form {
  max-width: 600px;
  margin: 0 auto;
}

.threshold-description {
  margin-left: 10px;
  color: #606266;
}

.template-selection {
  display: flex;
  flex-direction: column;
  gap: 30px;
}

.template-category h4 {
  margin-top: 0;
  margin-bottom: 15px;
  color: #2c3e50;
}

.template-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
  padding: 20px;
}

.template-card {
  cursor: pointer;
  transition: all 0.3s;
  border: 2px solid transparent;
}

.template-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
}

.template-card.selected {
  border-color: var(--el-color-primary);
}

.template-preview {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.preview-background {
  position: relative;
  width: 100%;
  height: 200px;
  background: linear-gradient(135deg, #f5f7fa 0%, #e4e8eb 100%);
  border: 1px solid #ebeef5;
  border-radius: 4px;
  overflow: hidden;
}

.background-image {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  object-fit: contain;
  object-position: center;
}

.preview-field {
  position: absolute;
  padding: 4px;
  background-color: rgba(255, 255, 255, 0.7);
  border-radius: 2px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 150px;
  font-size: 12px;
  pointer-events: none;
  transition: all 0.3s;
  z-index: 1;
}

.template-info {
  padding: 10px;
  background-color: #f8f9fa;
  border-radius: 4px;
}

.template-name {
  font-weight: bold;
  font-size: 16px;
  color: #303133;
  margin-bottom: 5px;
}

.template-date {
  font-size: 12px;
  color: #909399;
}

.field-mapping {
  margin-top: 20px;
}

.preview-summary {
  margin-top: 20px;
}

.template-summary {
  display: flex;
  flex-direction: column;
  gap: 10px;
  margin: 20px 0;
}

.template-item {
  display: flex;
  align-items: center;
}

.template-level {
  font-weight: bold;
  width: 100px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style> 